/**
 *
 */
package com.way.token.mobile.filter;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 *
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 验证码校验失败处理器
     */
    @Resource
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final String VALIDATION_CODE_KEY_PREFIX = "SMS_";


    /**
     * 初始化要拦截的url配置信息
     */
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
    }

    /*
     *
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        if (pathMatcher.match("/oauth/token", request.getRequestURI()) && "mobile".equals(request.getParameter("grant_type"))) {
            String mobile = request.getParameter("mobile");
            if (ObjectUtils.isEmpty(mobile)) {
                authenticationFailureHandler.onAuthenticationFailure(request, response,
                        new BadCredentialsException("手机号不能为空"));
                return;
            }
            String code = request.getParameter("code");
            if (ObjectUtils.isEmpty(code)) {
                authenticationFailureHandler.onAuthenticationFailure(request, response,
                        new BadCredentialsException("校验码不能为空"));
                return;
            }
            String key = VALIDATION_CODE_KEY_PREFIX + mobile;
            String codeInRedis = redisTemplate.opsForValue().get(key);
            if (!code.equals(codeInRedis)) {
                authenticationFailureHandler.onAuthenticationFailure(request, response, new BadCredentialsException("验证码校验不通过"));
                return;
            }
        }

//        ValidateCodeType type = getValidateCodeType(request);
//        if (type != null) {
//            logger.info("校验请求(" + request.getRequestURI() + ")中的验证码,验证码类型" + type);
//            try {
//                validateCodeProcessorHolder.findValidateCodeProcessor(type)
//                        .validate(new ServletWebRequest(request, response));
//                logger.info("验证码校验通过");
//            } catch (ValidateCodeException exception) {
//                authenticationFailureHandler.onAuthenticationFailure(request, response, exception);
//                return;
//            }
//        }

        chain.doFilter(request, response);

    }

}
